/*************************************************
Name : WebServicesUtil
Created By : dthekumparampil
Created Date : Jan 17, 2013
Description : A helper class which has certain common methods which can be shared among the Apex Webservices 
*******************************
Modified By : 
Modified Date : 
Modification : 	
*************************************************/

public with sharing class WebServicesUtil {

/**
Method Name : newOpportunityForAccount 
Created By : dthekumparampil
Created Date : Jan 17, 2013 
Description : This method is used to create a new opportunity for an account and disable all existing opportunities for the same.
Output : Boolean true or false.
**************************************
Modified By : dthekumparampil
Modified Date : Jan 28, 2013 
Modification :  Old opportunities are not disabled. 
				New Opportunity is created only if the status of existing opportunities of the Account is either
        		'Started' or 'Graduated' or 'Dropped' or 'Exited' or 'Declined' or 'No further Action'. Else a Case is created. 

**************************************
Modified By : dthekumparampil
Modified Date : Feb 21, 2013 
Modification :  Added additional parameter caseOrigin in method newOpportunityForAccount(). 
        		
**/
	
	public boolean newOpportunityForAccount(String accountId, String programID,
	String opportunityRecordTypeId, String lastName, String status, String subStatus, String startDate, String caseOrigin){
	
		/****Searching for existing Opportunity whose StageName is not 'Started', 'Graduated' or 'No further action' or 'Dropped' or 'Exited' or 'Declined'****/
		list<Opportunity> opportunityInSalesforce;
		
		opportunityInSalesforce = [select id, AccountId, RecordTypeId, StageName, CloseDate, IsClosed from Opportunity
		where AccountId=:accountId AND StageName!='Graduated' AND StageName!='Started' AND StageName!='Dropped' AND 
		StageName!='Exited' AND StageName!='Declined' AND StageName!='No Further Action' AND IsClosed=false];

		/****Adding Savepoint to revert incase of failure****/
		Savepoint opportunitySavepoint = Database.setSavepoint();
		
		if(opportunityInSalesforce.size()>0){
			/*Getting the RecordTypeId*/
			String caseRecordType = Schema.Sobjecttype.Case.getRecordTypeInfosByName().get('West - Support').getRecordTypeId();
			
			/*Create new Case for this account*/
			try{
				//Case owner gets updated for Cases created  by Web service due to Assignment rules / Support settings. 
        		//Hence we are Using field Manual_status_change__c to trigger the field update which will invoke Case trigger 
        		//and in turn will update the Queue ID for the Case. 
	        	Case newCase = new Case(AccountId=accountId,RecordTypeId=caseRecordType, Case_Name__c='Duplicate Opportunity', 
	        	Subject='Auto Created Case', Description='Auto Created Case',Manual_status_change__c=true, Origin=caseOrigin);
	        	insert newCase;
        	}
    		catch(Exception e){
    			system.debug('Account: unable to create case: '+e.getmessage());
    			Database.rollback(opportunitySavepoint);
    			return false;
    		}
			
			/* Old Logic of deactivating Opportunity
			for(Integer index =0; index<opportunityInSalesforce.size(); index++){
				opportunityInSalesforce[index].StageName='No Further Action';
				opportunityInSalesforce[index].CloseDate=Date.today();
			}
			try{
				update opportunityInSalesforce;
			}
			catch(DmlException de){
				Database.rollback(opportunitySavepoint);
				System.Debug('Problem in updating all the active Opportunities: '+de.getmessage());
				return false;
			}*/
		}
		else{
		/****Creating a new Opportunity and adding it to the Account provided****/
		
			Opportunity newOpportunity = new Opportunity();
			newOpportunity.AccountId = AccountId;
			newOpportunity.Program__c = programID;
			newOpportunity.RecordTypeId = opportunityRecordTypeId;
			newOpportunity.Name = lastName;
			newOpportunity.StageName = status;
			//newOpportunity.CloseDate = Date.today().addDays(10);// Business wants Close date same as Anticipated Start Date
			if(subStatus!=''){
				newOpportunity.Status_Detail__c = subStatus;
			}
			try{
				newOpportunity.Anticipated_Start_Date__c = Date.valueOf(startDate);
				newOpportunity.CloseDate = Date.valueOf(startDate);
				insert newOpportunity;
			}
			catch(DmlException de){
				Database.rollback(opportunitySavepoint);
				System.debug('Problem inserting the Opportunity: \n'+de.getMessage());
				return false;
			}
			catch(Exception e){
				Database.rollback(opportunitySavepoint);
				system.debug('Start Date Format Problem :\n'+e.getmessage());
				return false;
			}
		}
		/****When everything work perfectly****/
		return true;
	}
}